package com.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 非公平锁 实现交替打印
 * 
 * @author yaojinshan 2018-04-03 15:04
 *
 */
public class ReentrantLockTest {
	static int currentNum = 0;

	static void increate() {
		currentNum++;
	}

	static int getCurrentNum() {
		return currentNum;
	}

	public static void main(String[] args) {
		final Lock lock = new ReentrantLock();
		final Condition newCondition = lock.newCondition();
		final Condition newCondition1 = lock.newCondition();
		new Thread() {
			public void run() {
				while (getCurrentNum() < 100) {
					lock.lock();
					System.out.println(Thread.currentThread().getName() + "输出：" + getCurrentNum());
					increate();
					try {
						newCondition1.signal();// 唤起条件一
						newCondition.await();// 条件等待
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						lock.unlock();
					}
				}
			};
		}.start();

		new Thread() {
			public void run() {
				while (getCurrentNum() < 100) {
					lock.lock();
					System.out.println(Thread.currentThread().getName() + "输出：" + getCurrentNum());
					increate();
					try {
						newCondition.signal();
						newCondition1.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						lock.unlock();
					}
				}
			};
		}.start();
	}

}
